﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using System.Reflection;
using System.IO;
using Ahi.Config;
using Utilities.Logging;

namespace Ahi
{
    static class Program
    {
        public static MainForm MainForm { get; set; }
        private static Process mongoProcess;
        private static bool login = false;

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            System.Threading.Thread.CurrentThread.CurrentCulture =
                new System.Globalization.CultureInfo("tr-TR");

            System.Threading.Thread.CurrentThread.CurrentUICulture =
                new System.Globalization.CultureInfo("tr-TR");

            var lgn = new LoginForm();
            lgn.ShowDialog();

            if (login)
            {
                Program.MainForm = new Ahi.MainForm();
                Application.Run(Program.MainForm);
            }
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            HandleCrash((Exception)e.ExceptionObject);
        }

        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            HandleCrash(e.Exception);
        }

        static void HandleCrash(Exception exception)
        {
            try
            {
                CrashReportForm.ShowReport(exception, ALogger.Severity.Critical);
            }
            catch
            {
                MessageBox.Show("Hata raporu oluşturulurken hata oluştu :(");
            }
        }

        public static void StartMongoServer()
        {
            var procs = Process.GetProcessesByName("mongod");
            if (procs.Length > 0)
            {
                mongoProcess = procs[0];
                return;
            }

            var dbLock = Path.Combine(AppConfig.Current.DataDiziniDizini, "mongod.lock");
            if (File.Exists(dbLock)) File.Delete(dbLock);

            var exe = Path.Combine(AppConfig.Current.MongoDBDizini, "mongod.exe");
            if (!File.Exists(exe)) throw new FileNotFoundException("MongoDb Server bulunamadı!", exe);
            var command = "\"" + exe + "\"" + " --dbpath " + "\"" + AppConfig.Current.DataDiziniDizini + "\"" + " --smallfiles";

            ///MONGO Serveri başlatmak için 
            ///Uygulamanın ana dizininde bir bat dosyası oluştur
            File.WriteAllText(Path.Combine(AppConfig.Current.UygulamaDizini, "StartServer.bat"), command);
            var startInfo = new ProcessStartInfo("cmd.exe", "/C " + "StartServer.bat");
            startInfo.CreateNoWindow = true;
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            startInfo.UseShellExecute = false;
            mongoProcess = Process.Start(startInfo);

            //InstallMongoService();
        }

        //private static void InstallMongoService()
        //{
        //    var exe = Path.Combine(AppConfig.Current.MongoDBDizini, "mongod.exe");
        //    if (!File.Exists(exe)) throw new FileNotFoundException("MongoDb Server bulunamadı!", exe);
        //    var command = "\"" + exe + "\"" + " --logpath \"" + AppConfig.Current.LogDirectory + "\\mongoLog.txt\" --logappend --dbpath \"" + AppConfig.Current.DataDiziniDizini + "\"" + " --directoryperdb --install";

        //    ///MONGO Serveri kurmak için
        //    File.WriteAllText(Path.Combine(AppConfig.Current.UygulamaDizini, "InstallMongoService.bat"), command);
        //    var startInfo = new ProcessStartInfo("cmd.exe", "/C " + "InstallMongoService.bat");
        //    startInfo.CreateNoWindow = true;
        //    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        //    startInfo.UseShellExecute = false;
        //    mongoProcess = Process.Start(startInfo);
        //}

        public static void GetDatabase(string sunucu = null)
        {
            MongoAdaptor.Instance.Connect(sunucu);
            AppConfig.Current.LoadFromDatabase();
        }

        public static void StopMongoServer()
        {
            try
            {
                if (mongoProcess != null)
                    mongoProcess.Kill();
            }
            catch
            {
            }
        }

        internal static bool Login(string kullaniciAdi, string sifre, string veritabani)
        {
            if (!(kullaniciAdi.Equals("admin") && sifre.Equals("admin")))
            {
                MessageBox.Show("Kullanıcı adı veya şifre hatalı!", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (veritabani.Equals("localhost"))
            {
                try
                {
                    Program.StartMongoServer();
                }
                catch { }
            }

            try
            {
                Program.GetDatabase(veritabani);
            }
            catch (Exception ex)
            {
                CrashReportForm.ShowReport(new Exception("Veritabanı bağlantısı sağlanamadı. Lütfen bilgileri kontrol ediniz.", ex), ALogger.Severity.Critical);
            }
            login = true;
            return true;
        }
    }
}
